package com.ray.interceptor;

import com.ray.interceptor.base.AopContext;
import com.ray.interceptor.base.MetaObjectIntercept;
import com.ray.model.Department;
import com.ray.model.User;
import com.ray.util.Ret;
import com.ray.util.SerialNumberUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 权限拦截器
 * @package com.ray.interceptor.DepartmentIntercept
 * @author  Eddie_Ray
 * @date    2022年10月8日 上午9:48:58
 */
public class DepartmentIntercept extends MetaObjectIntercept {
	
	@Override
	public String queryBefore(AopContext ac) throws Exception {
		ac.sql += " and region = '"+ac.user.getRegion()+"' and is_delete = 0 ";
		return ac.sql;
	}

	@Override
	public Ret addBefore(AopContext ac) throws Exception {
		ac.record.set("no", "dp_"+ SerialNumberUtil.uuid(8));
		Department p = Department.dao.findFirst("select * from department where no = ? and region = ? and is_delete = 0",ac.record.getStr("no"),ac.user.getRegion());
		if(p!=null) {
			return Ret.fail("部门编号已存在，请勿重复添加！");
		}
		ac.record.set("region",ac.user.getStr("region"));
		return super.addBefore(ac);
	}
	
	@Override
	public Ret deleteAfter(AopContext ac) throws Exception {
		// TODO Auto-generated method stub
		List<User> users = User.dao.find("select * from user where find_in_set(?,department_no)",ac.record.getStr("no"));
		for (int i = 0; i < users.size(); i++) {
			User user = users.get(i);
			String[] dpts = user.getStr("department_no").split(",");
			List<String> temp = Arrays.asList(dpts);
			List<String> arrList = new ArrayList<String>(temp);
			arrList.remove(ac.record.getStr("no"));
			if(arrList.size()>0) {
				user.set("department_no", String.join(",", arrList));
			}else {
				Department dpt = Department.dao.findFirst("select * from department where region = ? and parent_no = '0'",ac.user.getStr("region"));
				user.set("department_no",dpt.getNo());
			}
			user.update();
		}
		return super.deleteAfter(ac);
	}
	
}
